package com.exam;

import java.util.Objects;
import java.util.function.Consumer;
@FunctionalInterface
interface MyConsumer<T> {
    void accept(T t);
}
public class MyArrayList<T> {
    public static void main(String[] args){
        MyArrayList<Integer> list = new MyArrayList();
        list.add(1);
        list.add(2);
        System.out.println(list);

    }
    private T[] list;
    private int size;
    private static final int CAPCITY = 10;
    MyArrayList(){
        list = (T[]) new Object[CAPCITY];
        size = 0;
    }
    public void add(T t){
        //考虑扩容
        if(list.length == size){
            T[] temp = (T[]) new Object[(int)(list.length * 1.5)];
            for(int i = 0;i < list.length;i++){
                temp[i] = list[i];
            }
            list = temp;
        }
        list[size] = t;
        size++;
    }
    public T get(int index){
        try{
            if(index < 0 || index >= list.length){
                throw new Exception("越界了");
            }
            return list[index];
        }
        catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }
    public void remove(int index){
        try{
            if(index < 0 || index >= size){
                throw new Exception("越界了");
            }
            for(int i = index;i < size - 1;i++){
                list[i] = list[i + 1];
            }
            size--;
        }
        catch (Exception e){
            System.out.println(e.getMessage());

        }
    }
    public int getSize(){
        return size;
    }
    public void forEach(Consumer<T> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept(list[i]);
        }
    }
    public String toString(){
        String result = "";
        for(int i = 0;i < size;i++){

            if(i == 0){
                result += "[";
            }
            if(i == size - 1){
                result += list[i] + "]";
            }else{
                result += list[i] + ", ";
            }

        }
        return result;
    }
}
